import com.sun.net.httpserver.HttpExchange;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.charset.StandardCharsets;
import com.google.gson.Gson;
import java.util.Map;
import java.util.HashMap;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.time.Instant;

import LunaServer.core.LunaServer;
import LunaServer.routing.Route;

/**
 * 用户路由处理器
 * 处理/user路径的请求
 */
public class UserRoute implements Route {
    private final LunaServer server;
    private final Gson gson = new Gson();

    public UserRoute(LunaServer server) {
        this.server = server;
    }

    /**
     * 处理HTTP请求
     * 
     * @param exchange HttpExchange对象
     * @return 响应内容
     */
    public String handleRequest(HttpExchange exchange) throws IOException {
        String response = "";
        int responseCode = 200;
        Gson gson = new Gson();
        Map<String, Object> result = new HashMap<>();

        try {
            // 根据不同的HTTP方法处理请求
            switch (exchange.getRequestMethod()) {
                case "GET":
                    response = handleGetRequest(exchange);
                    break;
                case "POST":
                    response = handlePostRequest(exchange);
                    break;
                case "PUT":
                    response = handlePutRequest(exchange);
                    break;
                case "DELETE":
                    response = handleDeleteRequest(exchange);
                    break;
                default:
                    result.put("error", "Method Not Allowed");
                    response = gson.toJson(result);
                    responseCode = 405;
                    break;
            }
        } catch (Exception e) {
            handleMethodNotAllowed(exchange);
        }

        // 发送响应
        exchange.getResponseHeaders().set("Content-Type", "application/json");
        exchange.sendResponseHeaders(responseCode, response.getBytes(StandardCharsets.UTF_8).length);

        OutputStream os = exchange.getResponseBody();
        os.write(response.getBytes(StandardCharsets.UTF_8));
        os.close();

        return response;
    }

    /**
     * 处理GET请求 - 获取用户信息
     */
    private String handleGetRequest(HttpExchange exchange) throws IOException {
        // 读取查询参数
        String query = exchange.getRequestURI().getQuery();
        Map<String, String> params = parseQueryParams(query);
        String userId = params.get("id");

        Map<String, Object> result = new HashMap<>();
        if (userId == null) {
            result.put("error", "Missing user id");
            return gson.toJson(result);
        }

        // 从数据库获取用户信息
        Map<String, Object> user = getUserById(userId);
        if (user != null) {
            return gson.toJson(user);
        } else {
            result.put("error", "User not found");
            return gson.toJson(result);
        }
    }

    /**
     * 处理POST请求 - 创建新用户
     */
    private String handlePostRequest(HttpExchange exchange) throws IOException {
        // 读取请求体
        String requestBody = "";
        try (InputStream is = exchange.getRequestBody()) {
            requestBody = new String(is.readAllBytes(), StandardCharsets.UTF_8);
        }

        // 解析用户数据
        Map<String, Object> userData = gson.fromJson(requestBody, Map.class);

        // 保存到数据库
        boolean success = createUser(userData);

        Map<String, Object> result = new HashMap<>();
        if (success) {
            result.put("success", true);
            result.put("message", "用户创建成功");
        } else {
            result.put("success", false);
            result.put("message", "用户创建失败");
        }

        return gson.toJson(result);
    }

    /**
     * 处理PUT请求 - 更新用户信息
     */
    private String handlePutRequest(HttpExchange exchange) throws IOException {
        // 读取请求体
        String requestBody = "";
        try (InputStream is = exchange.getRequestBody()) {
            requestBody = new String(is.readAllBytes(), StandardCharsets.UTF_8);
        }

        // 解析用户数据
        Map<String, Object> userData = gson.fromJson(requestBody, Map.class);

        // 更新数据库
        boolean success = updateUser(userData);

        Map<String, Object> result = new HashMap<>();
        if (success) {
            result.put("success", true);
            result.put("message", "用户更新成功");
        } else {
            result.put("success", false);
            result.put("message", "用户更新失败");
        }

        return gson.toJson(result);
    }

    /**
     * 处理DELETE请求 - 删除用户
     */
    private String handleDeleteRequest(HttpExchange exchange) throws IOException {
        // 读取查询参数
        String query = exchange.getRequestURI().getQuery();
        Map<String, String> params = parseQueryParams(query);
        String userId = params.get("id");

        Map<String, Object> result = new HashMap<>();
        if (userId == null) {
            result.put("error", "Missing user id");
            return gson.toJson(result);
        }

        // 从数据库删除用户
        boolean success = deleteUserById(userId);

        if (success) {
            result.put("success", true);
            result.put("message", "用户删除成功");
        } else {
            result.put("success", false);
            result.put("message", "用户删除失败");
        }

        return gson.toJson(result);
    }

    /**
     * 从数据库获取用户信息
     */
    private Map<String, Object> getUserById(String userId) {
        String dbUrl = server.getDbUrl(); // 使用服务器配置
        String dbUser = server.getDbUser(); // 使用服务器配置
        String dbPass = server.getDbPass(); // 使用服务器配置

        String sql = "SELECT id, username, email FROM users WHERE id = ?";

        try (Connection conn = DriverManager.getConnection(dbUrl, dbUser, dbPass);
                PreparedStatement pstmt = conn.prepareStatement(sql)) {

            pstmt.setInt(1, Integer.parseInt(userId));
            ResultSet rs = pstmt.executeQuery();

            if (rs.next()) {
                Map<String, Object> user = new HashMap<>();
                user.put("id", rs.getInt("id"));
                user.put("username", rs.getString("username"));
                user.put("email", rs.getString("email"));
                return user;
            }
        } catch (SQLException e) {
            System.err.println("Database error: " + e.getMessage());
            e.printStackTrace();
        }

        return null;
    }

    /**
     * 在数据库中创建新用户
     */
    private boolean createUser(Map<String, Object> userData) {
        String dbUrl = server.getDbUrl(); // 使用服务器配置
        String dbUser = server.getDbUser(); // 使用服务器配置
        String dbPass = server.getDbPass(); // 使用服务器配置

        String sql = "INSERT INTO users (username, password, email, age, is_active) VALUES (?, ?, ?, ?, ?)";

        try (Connection conn = DriverManager.getConnection(dbUrl, dbUser, dbPass);
                PreparedStatement pstmt = conn.prepareStatement(sql)) {

            pstmt.setString(1, (String) userData.get("username"));
            pstmt.setString(2, (String) userData.get("password"));
            pstmt.setString(3, (String) userData.get("email"));
            pstmt.setInt(4, ((Double) userData.get("age")).intValue());
            pstmt.setBoolean(5, (Boolean) userData.get("is_active"));

            int rowsAffected = pstmt.executeUpdate();
            return rowsAffected > 0;

        } catch (SQLException e) {
            System.err.println("Database error: " + e.getMessage());
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 更新数据库中的用户信息
     */
    private boolean updateUser(Map<String, Object> userData) {
        String dbUrl = server.getDbUrl(); // 使用服务器配置
        String dbUser = server.getDbUser(); // 使用服务器配置
        String dbPass = server.getDbPass(); // 使用服务器配置

        String sql = "UPDATE users SET username = ?, password = ?, email = ?, age = ?, is_active = ? WHERE id = ?";

        try (Connection conn = DriverManager.getConnection(dbUrl, dbUser, dbPass);
                PreparedStatement pstmt = conn.prepareStatement(sql)) {

            pstmt.setString(1, (String) userData.get("username"));
            pstmt.setString(2, (String) userData.get("password"));
            pstmt.setString(3, (String) userData.get("email"));
            pstmt.setInt(4, ((Double) userData.get("age")).intValue());
            pstmt.setBoolean(5, (Boolean) userData.get("is_active"));
            pstmt.setInt(6, ((Double) userData.get("id")).intValue());

            int rowsAffected = pstmt.executeUpdate();
            return rowsAffected > 0;

        } catch (SQLException e) {
            System.err.println("Database error: " + e.getMessage());
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 从数据库删除用户
     */
    private boolean deleteUserById(String userId) {
        String dbUrl = server.getDbUrl(); // 使用服务器配置
        String dbUser = server.getDbUser(); // 使用服务器配置
        String dbPass = server.getDbPass(); // 使用服务器配置

        String sql = "DELETE FROM users WHERE id = ?";

        try (Connection conn = DriverManager.getConnection(dbUrl, dbUser, dbPass);
                PreparedStatement pstmt = conn.prepareStatement(sql)) {

            pstmt.setInt(1, Integer.parseInt(userId));

            int rowsAffected = pstmt.executeUpdate();
            return rowsAffected > 0;

        } catch (SQLException e) {
            System.err.println("Database error: " + e.getMessage());
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 解析查询参数
     */
    private Map<String, String> parseQueryParams(String query) {
        Map<String, String> params = new HashMap<>();
        if (query != null) {
            String[] pairs = query.split("&");
            for (String pair : pairs) {
                String[] keyValue = pair.split("=");
                if (keyValue.length == 2) {
                    params.put(keyValue[0], keyValue[1]);
                }
            }
        }
        return params;
    }
}